<?php
/**
 * Created by PhpStorm.
 * User: 86151
 * Date: 2023/2/27
 * Time: 15:24
 */

namespace app\api\controller;
use app\admin\model\Ctrip;
use app\admin\model\Ctripinfo;
use app\common\controller\Api;
use think\Config;
use think\Db;
use think\Exception;
use app\admin\model\Auth;
use app\admin\model\Wxpay;
use app\admin\model\Index as IndexModel;
class Entryctrips extends Api
{
    protected $noNeedLogin = ['asfq'];
    protected $noNeedRight = ['*'];
    public function asfq(){
        $res=[
            'order_amount'=>20,
            'order_sn'=>1234568445
        ];
        $notify_urls="http://".$_SERVER['HTTP_HOST']."/api/wechat_notify/xcpay";
        $Info = 'H5订单支付';
        $objectxml = Wxpay::wx_pay_zh($res,$notify_urls,$Info,'oizk_5rkdlbosd-LFGNHyF_kGUuk');
        if($objectxml['return_code'] == 'FAIL'){
            Db::name('order')->where('id',1)->update(['status'=>3]);
            $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>1]));
            $this->error("购买失败,请咨询在线客服：4008772758",$strArr);
        }else{
            Db::name('cs')->insert(['info'=>json_encode($objectxml)]);
            $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>1,'result'=>$objectxml]));
            Db::name('cs')->insert(['info'=>$strArr]);
            $this->success("购买成功！~",$strArr);
        }
    }

    /**
     * 景点详情
     *
     * @ApiMethod (POST)
     * @param string $scenicspotid  景点id
     */
    public function ctrip(){
        $user_id = $this->auth->id;
        $userInfo = Auth::userInfo($user_id);
        $scenicspotid = input('scenicspotid');
        $resouceid =  input('resource_id');
        //景点基本信息
        $ctrip = Db::name('ctrip')->where('scenicspotid',$scenicspotid)
            ->field('name,address,commentgrade,star,ctripprice,opentimedesc,longitude,latitude,productdescription,cityname')
            ->find();
        //景点轮播图
        $images =  $this->picture($scenicspotid);
        $ctrip['images'] = $images;
        //景点详情
        $ctripinfo  = $this->getCtripInfo($scenicspotid);
        //景点简介
        $ctrip['productaddinfolist'] = $ctripinfo['productaddinfolist'];
        if( $ctrip['productaddinfolist'] == ''){
            $data = [];
        }else{
            //景点资源
            if(empty($resouceid)){
                $resources_ctrip = Db::name('resources_ctrip')->where('scenicspotid',$scenicspotid)->column('resouceid');
                $data = [];
                $categoryid = Db::name('resources_categoryid')->select();
                foreach ($resources_ctrip as $k=>$v){
                    $resources =  Db::name('ctrip_resources')
                        ->alias('a')
                        ->where('a.cansale','true')
                        ->join('resources_categoryid b','a.categoryid = b.categoryid')
                        ->where('a.resouceid',$v)
                        ->field('a.resouceid,a.name,a.price,a.ctripprice,a.categoryid,a.refundnewtype,a.advancebookingdays,a.advancebookingtime,a.sales,b.name as cname,a.isreservation')
                        ->find();
                    $res = $this->rli($resources['resouceid']);
                    if(count($res)>0){
                        $resources['ctripprice'] = $res['CtripPrice'];
                        $resources['price'] = $res['Price'];
                    }
                    $resources['ctripprice'] = $resources['price'];
                    if(isset($resources['categoryid'])){
                        foreach ($categoryid as $val){
                            if($resources['categoryid'] == $val['categoryid']){
                                $data[$resources['categoryid']]['title']=$val['name'];
                                $data[$resources['categoryid']]['content'][]=$resources;
                            }
                        }
                    }
                }
            }else{
                $resources_ctrip = Db::name('resources_ctrip')->where('scenicspotid',$scenicspotid)->where('resouceid',$resouceid)->value('resouceid');
                $data = [];
                $resources =  Db::name('ctrip_resources')
                    ->alias('a')
//                ->where('a.cansale','true')
                    ->join('resources_categoryid b','a.categoryid = b.categoryid')
                    ->where('a.resouceid',$resources_ctrip)
                    ->field('a.resouceid,a.name,a.price,a.ctripprice,a.categoryid,a.refundnewtype,a.advancebookingdays,a.advancebookingtime,a.sales,b.name as cname,a.isreservation')
                    ->find();
                $res = $this->rli($resources['resouceid']);
                if(count($res)>0){
                    $resources['ctripprice'] = $res['CtripPrice'];
                    $resources['price'] = $res['Price'];
                }
                $resources['ctripprice'] = $resources['price'];
                if($resources){
                    $categoryid = Db::name('resources_categoryid')->where('categoryid',$resources['categoryid'])->value('name');
                    $data[$resources['categoryid']]['title']=$categoryid;
                    $data[$resources['categoryid']]['content'][]=$resources;
                }

            }
        }


        $ctrip['resourcelist'] = $data;
        $ctrip['vip_id'] = $userInfo['vip_id'];
        $this->success('获取成功',$ctrip);
    }

    /**
     * 景点简介
     *
     * @ApiMethod (POST)
     * @param string $scenicspotid  景点id
     */
    public function ctripinfo(){
        $scenicspotid = input('scenicspotid');
        $res = Ctrip::send('menpiaojingdianxiangqing',[
            'ScenicSpotIDList'=>[$scenicspotid],
            'DistributionChannelID'=>'',
            'ImageSizeKey'=>'C_192_192_Q90',
            'SID'=>Config::get("ctrip.sid"),
            'AllianceID'=>Config::get("ctrip.aid")
        ]);
        $map['list'] = $res['ScenicSpotInfoList'][0]['ProductInfo'];
        $this->success('获取成功',$map);
    }
    /**
     * 资源简介
     *
     * @ApiMethod (POST)
     * @param string $resouceid  资源id
     */
    public function ticketinfo(){
        $resouceid =  input('resouceid');
        $res = Ctrip::send('menpiaoziyuanxiangqing',[
            'ResouceIDList'=>[$resouceid],
            'DistributionChannelID'=>'',
            'SID'=>Config::get("ctrip.sid"),
            'AllianceID'=>Config::get("ctrip.aid")
        ]);
        $this->success('获取成功',$res['ResourceList'][0]['ResourceAddInfoList']);
    }

    /**
     * 资源详情接口
     * @ApiMethod (POST)
     * @param  string $resouceid  资源id
     */
    public function ticket(){
        $resouceid =  input('resouceid');
        $res = Ctrip::send('menpiaoziyuanxiangqing',[
            'ResouceIDList'=>[$resouceid],
            'DistributionChannelID'=>'',
            'SID'=>Config::get("ctrip.sid"),
            'AllianceID'=>Config::get("ctrip.aid")
        ]);
        $data = $this->dynamicTicket($resouceid);
        $res['isemail'] = $data['IsNeedEmail'];
        $res['info'] = $data['ResourceList'][0];
        $this->success('获取成功',$res);
    }

    /**
     * 证件类型
     * @ApiMethod (POST)
     */
    public function cardtype(){
        $cardtype =  Db::name('ctrip_cardtype')->select();
        $this->success('获取成功',$cardtype);
    }

    /**
     * 下单附加信息全部信息
     *
     * @ApiMethod (POST)
     */
    public function certificate(){
        $certificate =  Db::name('certificate')->select();
        $this->success('获取成功',$certificate);
    }

    /**
     * 门票取证接口
     *
     * @ApiMethod (POST)
     * @param  string $orderid  携程订单id
     */
    public function voucher(){
        $orderid = input('orderid');
        $res = Ctrip::send('huoqumenpiaopinzheng',[
            'OrderId'=>$orderid,
            'SID'=>Config::get("ctrip.sid"),
            'VersionNO'=>'1.0',
            'AllianceID'=>Config::get("ctrip.aid")
        ]);
        $this->success('获取成功',$res);
    }

    /**
     * 单个日历
     */
    public function rli($resouceid){
        $res = Ctrip::send('menpiaojiagerili',[
            'ResourceIDList'=>[$resouceid],
            'StartDate'=>date('Y-m-d',time()),
            'EndDate'=>date('Y-m-d',time()+2*86400),
            'SID'=>Config::get("ctrip.sid"),
            'AllianceID'=>Config::get("ctrip.aid")
        ]);
        if(isset($res['ResourceList'][0]['DateList'])){
            $info['CtripPrice']=   $res['ResourceList'][0]['DateList'][0]['CtripPrice'];
            $info['Price'] = $res['ResourceList'][0]['DateList'][0]['Price'];
            return $info;
        }else{
            return [];
        }
    }

    public function orderrli($resouceid,$add_time){
        $user_id = $this->auth->id;
        $userInfo = Auth::userInfo($user_id);
        $res = Ctrip::send('menpiaojiagerili',[
            'ResourceIDList'=>[$resouceid],
            'StartDate'=>$add_time,
            'EndDate'=>$add_time,
            'SID'=>Config::get("ctrip.sid"),
            'AllianceID'=>Config::get("ctrip.aid")
        ]);
        if(isset($res['ResourceList'][0]['DateList'])){
           $ctripprice = $res['ResourceList'][0]['DateList'][0]['Price'];
        }else{
            exit(json_encode(array('code' =>0, 'msg' =>'暂时不支持购买'), JSON_UNESCAPED_UNICODE));
        }
        return $ctripprice;
    }

    /**
     * 门票日历价格
     *
     * @ApiMethod (POST)
     * @param  string $resouceid  资源id
     */
    public function moneyTicket(){
        $user_id = $this->auth->id;
        $userInfo = Auth::userInfo($user_id);
        $resouceid = input('resouceid');
        $res = Ctrip::send('menpiaojiagerili',[
            'ResourceIDList'=>[$resouceid],
            'StartDate'=>date('Y-m-d',time()),
            'EndDate'=>date('Y-m-d',time()+30*86400),
            'SID'=>Config::get("ctrip.sid"),
            'AllianceID'=>Config::get("ctrip.aid")
        ]);
        if(isset($res['ResourceList'][0]['DateList'])){
            foreach ($res['ResourceList'][0]['DateList'] as &$v){
                $v['yuanjia'] =  round($v['CtripPrice']*0.2+$v['CtripPrice'],2);
                $v['CtripPrice'] = $v['Price'];
            }
        }
        $this->success('获取成功',$res);
    }

    //获取景点详情
    public function getCtripInfo($scenicspotid){
        $res = Ctrip::send('menpiaojingdianxiangqing',[
            'ScenicSpotIDList'=>[$scenicspotid],
            'DistributionChannelID'=>'',
            'ImageSizeKey'=>'C_192_192_Q90',
            'SID'=>Config::get("ctrip.sid"),
            'AllianceID'=>Config::get("ctrip.aid")
        ]);
        $map['productaddinfolist']='';
        if(isset($res['ScenicSpotInfoList'][0]['ProductInfo']['ProductAddInfoList'])){
            $map['productaddinfolist'] = $res['ScenicSpotInfoList'][0]['ProductInfo']['ProductAddInfoList'];
        }
        return $map;
    }

    /**
     * 门票动态表单
     *
     * @ApiMethod (POST)
     * @param  string $orderid  携程订单id
     */
    public function dynamicTicket($resouceid){
        $res = Ctrip::send('menpiaodongtaibiaodan',[
            'ResourceIDList'=>[$resouceid],
            'SID'=>Config::get("ctrip.sid"),
            'AllianceID'=>Config::get("ctrip.aid")
        ]);
        return $res;
    }
    //景点图片接口
    public function picture($scenicspotid){
        $res = Ctrip::send('jingdiantupianjiekou',[
            'ImageSizeKeyList'=>['C_500_280_Q90'],
            'ImageLimit'=>0,
            'ScenicSpotIDList'=>[$scenicspotid],
            'SID'=>Config::get("ctrip.sid"),
            'DistributionChannelId'=>9,
            'AllianceID'=>Config::get("ctrip.aid")
        ]);
        if(isset($res['ScenicSpotImageList'][0]['ImageSizeMapList'][0]['ImageURLList'])){
            return $res['ScenicSpotImageList'][0]['ImageSizeMapList'][0]['ImageURLList'];
        }else{
            return $data=[];
        }
    }



    // 门票可退检查
    public function retreatOrder($orderid){
        $res = Ctrip::send('menpiaoketuijiancha',[
            'OrderId'=>$orderid,
            'SID'=>Config::get("ctrip.sid"),
            'AllianceID'=>Config::get("ctrip.aid")
        ]);
        return $res;
    }

    //门票退单
    public function drawbackOrder($orderid,$content,$OrderItemID,$RefundQuantity,$RefundOtherRequirement,$uid,$datadf=[]){
        if($RefundOtherRequirement == 2){
            $info =[[
                'OrderItemID'=>$OrderItemID,
                'Quantity'=>$RefundQuantity,
                'ClientIdList'=>$datadf,
            ]];
        }else{
            $info =[];
        }
        $res = Ctrip::send('menpiaotuidan',[
            'DistributionChannelId'=>9,
            'OrderId'=>$orderid,
            'Reason'=>$content,
            'OrderVerifys'=>[[
                'VerifyKey'=>'UID',
                'VerifyValue'=>$uid,
            ]],
            'PortionRefundItems'=>$info,
            'SID'=>Config::get("ctrip.sid"),
            'AllianceID'=>Config::get("ctrip.aid")
        ]);
        return $res;
    }


    /**
     * 售中退款
     *
     * @ApiMethod (POST)
     * @param int $voucher_id 凭证ID
     * @param int $reason 退款原因
     * @param string $token token
     */
    public function refund(){
        $user_id = $this->auth->id;
        $userInfo = Auth::userInfo($user_id);
        if($userInfo['vip_id'] == 0){
            $sfvip = Db::name('sanfang_vip')->where('end_time','>',time())->where('is_att',3)->where('is_t',0)->where('mobile',$userInfo['mobile'])->value('vip_id');
            if($sfvip){
                $userInfo['vip_id'] =$sfvip;
            }
        }
        $order_id =  input('order_id');
        $reason = input("reason");//退款原因
        if(!$order_id){
            $this->error('参数不全');
        }
        $order = Db::name("order")->where('id',$order_id)->find();
        if($order['from']==2){
            //兑换的订单不作退还
            $this->error("该订单属于会员专享兑换权益，不支持退换，详情请咨询在线客服：4008772758");
        }
        //检查门票
        $res = $this->retreatOrder($order['outer_order_id']);
        if($res['ResultStatus']['IsSuccess'] === true){
            if($res['CancelItems'][0]['CancelItemStatus'] == 0){
                $this->error('该门票，不可退');
            }else{
                //退票
                if($res['CancelItems'][0]['RefundOtherRequirement'] == 2){
                    $datadf=[];
                    if(isset($res['CancelItems'][0]['RefundOtherRequirement'])){
                        $data=[];
                        foreach ($res['CancelItems'][0]['clientInfoList'] as $v){
                            $data['ClientID'] = $v['ClientID'];
                        }
                        if(count($data)>0){
                            $datadf[] = $data;
                        }
                    }
                    $data = $this->drawbackOrder($order['outer_order_id'],$reason,$res['CancelItems'][0]['OrderItemID'],$res['CancelItems'][0]['RefundQuantity'],$res['CancelItems'][0]['RefundOtherRequirement'],$order['uid'],$datadf);
                }else{
                    $data = $this->drawbackOrder($order['outer_order_id'],$reason,$res['CancelItems'][0]['OrderItemID'],$res['CancelItems'][0]['RefundQuantity'],$res['CancelItems'][0]['RefundOtherRequirement'],$order['uid']);
                }
                if($data['ResultStatus']['IsSuccess'] === true){
                    Db::name('order')->where('order_no',$order['order_no'])->update(['status'=>5,'cs'=>json_encode($data)]);
                    if($res['CancelItems'][0]['CancelItemStatus'] == 1){
                        if($order['amount']>0){
                            if($res['CancelItems'][0]['RefundCostType'] == 1){
                                $div = bcdiv($res['CancelItems'][0]['RefundCostValue'],100,2);
                                $mul = bcmul($res['CancelItems'][0]['RefundCostValue'],$div,2);
                                $amount =  $order['amount'] - $mul;
                            }else if($res['CancelItems'][0]['RefundCostType'] == 2){
                                $amount =  $order['amount'] - $res['CancelItems'][0]['RefundCostValue'];
                            }else{
                                $amount =  $order['amount'];
                            }
                            Wxpay::doRefund($order['amount'],$amount,$order['order_no'],$order['transaction_id'],$reason);
                        }
                        Db::name('order')->where('id',$order_id)->update(['status'=>5,'rund_time'=>time(),'rund_info'=>$reason]);
                        Db::name('voucher')->where('order_id',$order_id)->update(['voucher_status'=>'CANCELED']);
                        $this->success($data['ResultStatus']['ErrorMessage']);
                    }else{
                        $this->success('转人工流程');
                    }
                }else{
                    Db::name('order')->where('order_no',$order['order_no'])->update(['cs'=>json_encode($data)]);
                    $this->error($data['ResultStatus']['ErrorMessage']);
                }

            }
        }else{
            $this->error('退款失败,联系工作人员');
        }
    }

    /**
     * 携程正常下单
     */
    public function createOrder(){
        $type = 3;
        $user_id = $this->auth->id;
        $userInfo = Auth::userInfo($user_id);
        $datainfo = IndexModel::setDecryptArray(Config::get("miyao.shi"),input());
        $datainfo = json_decode($datainfo,true);
//        dump($datainfo);die;
        //正常购买
        $resource_id = $datainfo['resource_id'];
        $num = $datainfo['num'];//购买数量
        $yuanjia = $datainfo['yuanjia'];//原价
        $scenicspotid = $datainfo['scenicspotid']; //景点id
        $resouceid =$resource_id; //资源id
        $time = $datainfo['time']; //购买时间
        $price =$datainfo['price']; //购买分销价
//        $ctripprice = $price;  //总价
        if($userInfo['vip_id']>0){
            $ctripprice = $price * $num;
        }else{
            $jiage = $this->orderrli($resouceid,$time);
            $ctripprice = $jiage * $num;
        }
        $cx_num =$datainfo['cx_num']; //出行人数量
        $contactinfo =$datainfo['contactinfo'];
        if($contactinfo){
            $contactinfo = htmlspecialchars_decode($contactinfo); //联系人信息
        }
        $passenerinfolist = $datainfo['passenerinfolist'];
        if($passenerinfolist){
            $passenerinfolist = htmlspecialchars_decode($passenerinfolist); //出行人信息
        }
        $itemaddinfos = '';
        $order_no = makeOrderNum();
        //检查订票信息
        $res = Ctripinfo::inspectTicket($resouceid,$time,$num,$price,$contactinfo,$passenerinfolist);
        if($res['ResultStatus']['IsSuccess'] === false){
            $this->error('不符合订票流程');
        }
        $discount_amount = $yuanjia - bcmul($price,$num,2);
        $from = 1;
        $title =  Db::name('ctrip_resources')->where('resouceid',$resouceid)->value('name');
        $main_picture =Db::name('ctrip')->where('scenicspotid',$scenicspotid)->value('url_image');
        //生成订单
        $order = Ctripinfo::xcorder($userInfo['id'],$order_no,$type,$resource_id,$ctripprice,$num,0,$scenicspotid,$price,$cx_num,$contactinfo,$passenerinfolist,$itemaddinfos,$time,0,$discount_amount,$title,$main_picture,$from,0);
        if($order){
            //微信支付
            if($ctripprice>0){
                $res=[
                    'order_amount'=>$ctripprice,
                    'order_sn'=>$order_no
                ];
                $notify_urls="http://".$_SERVER['HTTP_HOST']."/api/wechat_notify/xcpay";
                $Info = 'H5订单支付';
                $objectxml = Wxpay::wx_pay_zh($res,$notify_urls,$Info,$userInfo['gzh_open_id']);
                if($objectxml['return_code'] == 'FAIL'){
                    Db::name('order')->where('id',$order)->update(['status'=>3]);
                    $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$order]));
                    $this->error("购买失败,请咨询在线客服：4008772758",$strArr);
                }else{
                    $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$order,'result'=>$objectxml]));
                    $this->success("购买成功！~",$strArr);
                }
            }else{
                Db::name('order')->where('id',$order)->update(['status'=>3]);
                $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$order]));
                $this->error("购买失败,请咨询在线客服：4008772758",$strArr);
            }
        }else{
            $this->error("订单创建失败");
        }
    }

    /**
     * 会员权益购买
     */
    public function VipcreateOrder(){
        $user_id = $this->auth->id;
        $userInfo  = Auth::userInfo($user_id);
        $qinghai = 0; //会员五  青海类型
        $datainfo = IndexModel::setDecryptArray(Config::get("miyao.shi"),input());
        $datainfo = json_decode($datainfo,true);
        if(!isset($datainfo['sanfang'])){
            $datainfo['sanfang'] = 0;
        }
        //会员专区购买
        $zone_id = $datainfo['zone_id'];
        $class_id =$datainfo['class_id'];
        $resource_id = $datainfo['resource_id'];
        $sanfang =$datainfo['sanfang'];
        if($sanfang){
            $vip_id =$datainfo['vip_id'];
            $userInfo['vip_id'] = $vip_id;
        }
        if($sanfang){  //三方兑换验证
            $sanfang_vip = Db::name("sanfang_vip")->where('vip_id',$vip_id)->where(['mobile' => $userInfo['mobile']])->where('is_t', 0)->find();
            if ($sanfang_vip) {
                if($sanfang_vip['is_att'] == 3){
                    $qinghao = Db::name('qinghao')->where('mobile',$userInfo['mobile'])->where('zone_id', $zone_id)->where('is_do', 0)->where('end_time', '>', time())->find();
                    if (!$qinghao) {
                        exit(json_encode(array('code' => 0, 'msg' => '会员兑换权益已用完！'), JSON_UNESCAPED_UNICODE));
                    }
                    $qinghai = $qinghao['id'];
                }
            } else {
                exit(json_encode(array('code' =>0, 'msg' =>'您未加入该会员'), JSON_UNESCAPED_UNICODE));
            }
        }else {
            if ($zone_id) {
                $operator_vip = Db::name('operator_vip')->where('id', $userInfo['vip_id'])->field('id,type,exchange_count,rules')->find();
               if ($operator_vip['type'] == 5) {
                    $qinghao = Db::name('qinghao')->where('mobile', $userInfo['mobile'])->where('zone_id', $zone_id)->where('is_do', 0)->where('end_time', '>', time())->find();
                    if (!$qinghao) {
                        exit(json_encode(array('code' => 0, 'msg' => '会员兑换权益已用完！'), JSON_UNESCAPED_UNICODE));
                    }
                    $qinghai = $qinghao['id'];
                }
            }
        }
        $type = 3;
        $num = 1;//购买数量
        $scenicspotid =$datainfo['scenicspotid']; //景点id
        $resouceid =$resource_id; //资源id
        $time = $datainfo['time']; //购买时间
        $price =  $datainfo['price']; //购买分销价
        $cx_num =  $datainfo['cx_num']; //出行人数量
        $contactinfo = $datainfo['contactinfo'];
        if($contactinfo){
            $contactinfo = htmlspecialchars_decode($contactinfo); //联系人信息
        }
        $passenerinfolist = $datainfo['passenerinfolist'];
        if($passenerinfolist){
            $passenerinfolist = htmlspecialchars_decode($passenerinfolist); //出行人信息
        }
        $itemaddinfos ='';//附加信息
        if($zone_id){
            $kc = Db::name('order')->where('zone_id', $zone_id)->where('class_id', $class_id)->where('resource_id', $resource_id)->whereTime('createtime', 'today')->count();
            $day_num = Db::name('operator_exchange_goods')->where('zone_id', $zone_id)->where('cla_id', $class_id)->where('resource_id', $resource_id)->value('day_num');
            if ($kc >= $day_num) {
                exit(json_encode(array('code' => 0, 'msg' => '今日已售罄，请明日再来'), JSON_UNESCAPED_UNICODE));
            }
            $exchange_goods = Db::name('operator_exchange_goods')->where('vip_id', $userInfo['vip_id'])->where('zone_id', $zone_id)->where('cla_id', $class_id)->where('resource_id', $resource_id)->find();
            if($exchange_goods['xy'] == 1 || !$exchange_goods){
                $this->error("商品下架,请明日再来");exit;
            }
            $discount_amount = $exchange_goods['fsj'] - $exchange_goods['vip_money'];
            $jiage = $this->orderrxcj($resource_id,$time);
            $ctripprice = round($jiage - $exchange_goods['xc_price'],2);//会员价价
        }
        if($ctripprice<=0){
            $this->error("流程错误");exit;
        }
        if(empty($resource_id)){
            $this->error("参数不全");exit;
        }
        $order_no = makeOrderNum();
        //检查订票信息
        $res = Ctripinfo::inspectTicket($resouceid,$time,$num,$price,$contactinfo,$passenerinfolist);
        if($res['ResultStatus']['IsSuccess'] === false){
            $this->error('不符合订票流程');
        }
        $from = 2;
        $coupon_amount =0;
        $title =  Db::name('ctrip_resources')->where('resouceid',$resouceid)->value('name');
        $main_picture =Db::name('ctrip')->where('scenicspotid',$scenicspotid)->value('url_image');
        //生成订单
        $order = Ctripinfo::xcorder($userInfo['id'],$order_no,$type,$resource_id,$ctripprice,$num,0,$scenicspotid,$price,$cx_num,$contactinfo,$passenerinfolist,$itemaddinfos,$time,$coupon_amount,$discount_amount,$title,$main_picture,$from,0,$zone_id,$class_id,$userInfo['mobile'],0,$qinghai);
        if($order){
            //微信支付
            if($ctripprice>0){
                $res=[
                    'order_amount'=>$ctripprice,
                    'order_sn'=>$order_no
                ];
                $notify_urls="http://".$_SERVER['HTTP_HOST']."/api/wechat_notify/xcpay";
                $Info = 'H5订单支付';
                $objectxml = Wxpay::wx_pay_zh($res,$notify_urls,$Info,$userInfo['gzh_open_id']);
                if($objectxml['return_code'] == 'FAIL'){
                    Db::name('order')->where('id',$order)->update(['status'=>3]);
                    $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$order]));
                    $this->error("购买失败,请咨询在线客服：4008772758",$strArr);
                }else{
                    $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$order,'result'=>$objectxml]));
                    $this->success("购买成功！~",$strArr);
                }
            }else{
                Db::name('order')->where('id',$order)->update(['status'=>3]);
                $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$order]));
                $this->error("购买失败,请咨询在线客服：4008772758",$strArr);
            }
        }else{
            $this->error("订单创建失败");
        }
    }



    /**
     * 携程兑换
     */
    public function exchange(){
        $user_id = $this->auth->id;
        $userInfo  = Auth::userInfo($user_id);
        $qinghai  = 0; //青海类型
        //权益兑换
        $datainfo = IndexModel::setDecryptArray(Config::get("miyao.shi"),input());
        $datainfo = json_decode($datainfo,true);
        if(!isset($datainfo['sanfang'])){
            $datainfo['sanfang'] = 0;
        }
        $zone_id = $datainfo['zone_id'];//会员专区id
        $class_id =$datainfo['class_id'];//分类id
        $type = 3;
        $resource_id =$datainfo['resource_id'];
        $num =1;
        $sanfang =$datainfo['sanfang'];
        if($sanfang){
            $vip_id =$datainfo['vip_id'];
            $userInfo['vip_id'] = $vip_id;
        }
        $scenicspotid = $datainfo['scenicspotid']; //景点id
        $resouceid =$resource_id; //资源id
        $time = $datainfo['time']; //购买时间
        $price = $datainfo['price']; //购买分销价
        $cx_num =  $datainfo['cx_num']; //出行人数量
        $contactinfo = $datainfo['contactinfo'];
        if($contactinfo){
            $contactinfo = htmlspecialchars_decode($contactinfo); //联系人信息
        }
        $passenerinfolist =  $datainfo['passenerinfolist'];
        if($passenerinfolist){
            $passenerinfolist = htmlspecialchars_decode($passenerinfolist); //出行人信息
        }
        $itemaddinfos ='';//附加信息
        $order_no = makeOrderNum();
        $res = Ctripinfo::inspectTicket($resouceid,$time,$num,$price,$contactinfo,$passenerinfolist);
        if($res['ResultStatus']['IsSuccess'] === false){
            $this->error('不符合购票流程');
        }
        $coupon_id =0;
        //生成订单
        $title =  Db::name('ctrip_resources')->where('resouceid',$resouceid)->value('name');
        $main_picture =Db::name('ctrip')->where('scenicspotid',$scenicspotid)->value('url_image');
        $order = 0;
        if($zone_id){
            $kc = Db::name('order')->where('zone_id', $zone_id)->where('class_id', $class_id)->where('resource_id', $resource_id)->whereTime('createtime', 'today')->count();
            $day_num = Db::name('operator_exchange_goods')->where('zone_id', $zone_id)->where('cla_id', $class_id)->where('resource_id', $resource_id)->value('day_num');
            if ($kc >= $day_num) {
                exit(json_encode(array('code' => 0, 'msg' => '今日已售罄，请明日再来'), JSON_UNESCAPED_UNICODE));
            }
            $exchange_goods = Db::name('operator_exchange_goods')->where('vip_id', $userInfo['vip_id'])->where('zone_id', $zone_id)->where('cla_id', $class_id)->where('resource_id', $resource_id)->find();
            if($exchange_goods['xy'] == 1 || !$exchange_goods){
                $this->error("商品下架,请明日再来");exit;
            }
            $jiage = $this->orderrxcj($resource_id,$time);
            $ctripprice = round($jiage - $exchange_goods['xc_price'],2);//会员价价
            if($ctripprice<0){
                $ctripprice = 0;
            }
        }
        if($ctripprice>0){
            $this->error("流程错误");exit;
        }
        if($sanfang){  //三方兑换验证
            Db::startTrans();
            try {
                $sanfang_vip = Db::name("sanfang_vip")->where('vip_id',$vip_id)->where(['mobile' => $userInfo['mobile']])->where('is_t', 0)->find();
                if ($sanfang_vip) {
                    if($sanfang_vip['is_att'] == 3){
                        $qinghao = Db::name('qinghao')->where('mobile',$userInfo['mobile'])->where('zone_id',$zone_id)->where('is_do',0)->where('end_time','>',time())->lock(true)->find();
                        if(!$qinghao){
                            Db::rollback();
                            exit(json_encode(array('code' =>0, 'msg' =>'会员兑换权益已用完！'), JSON_UNESCAPED_UNICODE));
                        }
                        Db::name('qinghao')->where('id',$qinghao['id'])->update(['is_do'=>1]);
                        $qinghai = $qinghao['id'];
                    }
                } else {
                    Db::rollback();
                    exit(json_encode(array('code' =>0, 'msg' =>'您未加入该会员'), JSON_UNESCAPED_UNICODE));
                }
                $discount_amount= Db::name("operator_exchange_goods")->where(['resource_id' => $resource_id])->value('fsj');
                $order = Ctripinfo::xcorder($userInfo['id'], $order_no, $type, $resouceid, $ctripprice, $num, $coupon_id, $scenicspotid, $price, $cx_num, $contactinfo, $passenerinfolist, $itemaddinfos, $time, $coupon_amount = 0, $discount_amount , $title, $main_picture, $from = 2, $flash_sale_id = 0, $zone_id, $class_id, $userInfo['mobile'],'',$qinghai,input('position'),$userInfo['card']);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                exit(json_encode(array('code' =>0, 'msg' =>$e), JSON_UNESCAPED_UNICODE));
            }
        }else {
            if ($zone_id) {
                Db::startTrans();
                try {
                    $operator_vip = Db::name('operator_vip')->where('id', $userInfo['vip_id'])->field('id,type,exchange_count,rules')->find();
                   if ($operator_vip['type'] == 5) {
                        $qinghao = Db::name('qinghao')->where('mobile', $userInfo['mobile'])->where('zone_id', $zone_id)->where('is_do', 0)->where('end_time', '>', time())->lock(true)->find();
                        if (!$qinghao) {
                            Db::rollback();
                            exit(json_encode(array('code' => 0, 'msg' => '会员兑换权益已用完！'), JSON_UNESCAPED_UNICODE));
                        }
                        Db::name('qinghao')->where('id', $qinghao['id'])->update(['is_do' => 1]);
                        $qinghai = $qinghao['id'];
                    }
                    $discount_amount = Db::name("operator_exchange_goods")->where('cla_id', $class_id)->where(['resource_id' => $resource_id])->value('fsj');
                    $order = Ctripinfo::xcorder($userInfo['id'], $order_no, $type, $resouceid, $ctripprice, $num, $coupon_id, $scenicspotid, $price, $cx_num, $contactinfo, $passenerinfolist, $itemaddinfos, $time, $coupon_amount = 0, $discount_amount, $title, $main_picture, $from = 2, $flash_sale_id = 0, $zone_id, $class_id, $userInfo['mobile']);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    exit(json_encode(array('code' => 0, 'msg' => $e), JSON_UNESCAPED_UNICODE));
                }
            }
        }
        if($order){
            $order =  Db::name('order')->where('id',$order)->find();
            $res = Ctripinfo::Ordercreate($order['order_no'],$order['scenicspotid'],$order['resource_id'],$order['time'],$order['num'],$order['price'],$order['cx_num'],$order['contactinfo'],$order['passenerinfolist'],$order['itemaddinfos']);
            if($res['ResultStatus']['IsSuccess'] === true){
                Db::startTrans();
                try {
                    Db::name('order')->where([
                        'order_no' => $order['order_no']
                    ])->update([
                        'outer_order_id' => $res['OrderID'],
                        'biz_order_id' => $res['TradeNo'],
                        'status' => 2
                    ]);
                    if ($zone_id) {
                        //添加销量
                        Db::name('ctrip')->where('scenicspotid', $order['scenicspotid'])->setInc('ctrip_sales', $order['num']);
                        Db::name('ctrip_resources')->where('resouceid', $order['resource_id'])->setInc('sales', $order['num']);
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    exit(json_encode(array('code' =>0, 'msg' =>$e), JSON_UNESCAPED_UNICODE));
                }
                $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$order['id']]));
                $this->success("兑换成功,请前往个人中心查看。",$strArr);
            }else{
                Db::name("order")->where(['order_no' => $order['order_no']])->update(['status' => 3]);
                if($qinghai > 0){
                    Db::name('qinghao')->where('id',$qinghai)->update(['is_do'=>0]);
                }
                $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$order['id']]));
                $this->error("购买失败",$strArr);
            }
        }else{
            $this->error("订单创建失败");
        }
    }


    //xcj
    public function orderrxcj($resouceid,$add_time){
        $res = Ctrip::send('menpiaojiagerili',[
            'ResourceIDList'=>[$resouceid],
            'StartDate'=>$add_time,
            'EndDate'=>$add_time,
            'SID'=>Config::get("ctrip.sid"),
            'AllianceID'=>Config::get("ctrip.aid")
        ]);
        if(isset($res['ResourceList'][0]['DateList'])){
            $ctripprice = $res['ResourceList'][0]['DateList'][0]['CtripPrice'];
        }else{
            exit(json_encode(array('code' =>0, 'msg' =>'暂时不支持兑换'), JSON_UNESCAPED_UNICODE));
        }
        return $ctripprice;
    }
}